<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="单位名称" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入单位名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位地址" prop="unitAddress">
        <el-input
          v-model="queryParams.unitAddress"
          placeholder="请输入单位地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="信用代码" prop="creditCode">
        <el-input
          v-model="queryParams.creditCode"
          placeholder="请输入信用代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开户行" prop="bankInfo">
        <el-input
          v-model="queryParams.bankInfo"
          placeholder="请输入开户行"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="银行账号" prop="bankAccount">
        <el-input
          v-model="queryParams.bankAccount"
          placeholder="请输入银行账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactUser">
        <el-input
          v-model="queryParams.contactUser"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactNumber">
        <el-input
          v-model="queryParams.contactNumber"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信号" prop="weixin">
        <el-input
          v-model="queryParams.weixin"
          placeholder="请输入微信号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:customer:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="customerId" />
      <el-table-column label="客户名称" align="center" prop="unitName" />
      <el-table-column label="单位地址" align="center" prop="unitAddress" />
      <el-table-column label="信用代码" align="center" prop="creditCode" />
      <el-table-column label="开户行" align="center" prop="bankInfo" />
      <el-table-column label="银行账号" align="center" prop="bankAccount" />
      <el-table-column label="联系人" align="center" prop="contactUser" />
      <el-table-column label="联系电话" align="center" prop="contactNumber" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="微信号" align="center" prop="weixin" />
      <el-table-column label="冻结(是/否)" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:customer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:customer:remove']"
          >删除</el-button>
          <!--<el-button-->
            <!--size="mini"-->
            <!--type="text"-->
            <!--icon="el-icon-link"-->
            <!--@click="contractManager(scope.row.customerId)"-->
            <!--v-hasPermi="['system:customer:remove']"-->
          <!--&gt;合同管理</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false" v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位地址" prop="unitAddress">
          <el-input v-model="form.unitAddress" placeholder="请输入单位地址" />
        </el-form-item>
        <el-form-item label="信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入信用代码" />
        </el-form-item>
        <el-form-item label="开户行" prop="bankInfo">
          <el-input v-model="form.bankInfo" placeholder="请输入开户行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input v-model="form.contactUser" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="微信号" prop="weixin">
          <el-input v-model="form.weixin" placeholder="请输入微信号" />
        </el-form-item>
        <!--<el-form-item label="状态">-->
          <!--<el-radio-group v-model="form.status">-->
            <!--<el-radio-->
              <!--v-for="dict in dict.type.sys_normal_disable"-->
              <!--:key="dict.value"-->
              <!--:label="dict.value"-->
            <!--&gt;{{dict.label}}</el-radio>-->
          <!--</el-radio-group>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {changeCustomerStatus, listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, exportCustomer, getCustomerByuserId} from "@/api/system/customer";
import Cookies from 'js-cookie'


var bankAccountValid = (rule, value, callback) => {
  const strBin = '10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99'
  if (!value) {
    return callback(new Error('银行卡号不能为空'))
  } else if (!Number.isInteger(+value)) {
    callback(new Error('银行卡号必须全为数字'))
  } else if (value.trim().length < 12 || value.trim().length > 19) {
    callback(new Error('银行卡号长度必须在12到19之间'))
  } else if (strBin.indexOf(value.substring(0, 2)) === -1) {
    callback(new Error('银行卡号开头6位不符合规范'))
  } else {
    callback()
  }
}


export default {
  name: "Customer",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitName: null,
        unitAddress: null,
        creditCode: null,
        bankInfo: null,
        bankAccount: null,
        contactUser: null,
        contactNumber: null,
        email: null,
        weixin: null,
        post: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 日期范围
      dateRange: [],
      // 表单校验
      rules: {
        unitName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '单位名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        unitAddress: [
          { required: true, message: "单位地址不能为空", trigger: "blur" },
          { min: 5, max: 40, message: '单位名称长度必须介于 5 和 40 之间', trigger: 'blur' }
        ],
        creditCode: [
          { required: true, message: "统一社会信用代码不能为空.", trigger: "blur" },
          {
            type: "string",
            max: 18,
            message: "输入有误，统一社会信用代码长度需为18位",
            trigger: "change"
          },
          {
            type: "string",
            /*
           统一社会信用代码由十八位的阿拉伯数字或大写英文字母（不使用I、O、Z、S、V）组成。
            第1位：登记管理部门代码（共一位字符）登记管理部门代码：使用阿拉伯数字或大写英文字母表示。​
            第2位：机构类别代码（共一位字符）
            第3位~第8位：登记管理机关行政区划码（共六位阿拉伯数字）
            第9位~第17位：主体标识码（组织机构代码）（共九位字符）
            第18位：校验码​（共一位字符）
            */
            /* pattern: /[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}/g,*/
            pattern: /^([1,5,9][1,2,3,9]|[2,3,4,6,7,8,A,B,C,D,E,G,Y]1)\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/,
            message: "请输入正确的统一社会信用代码",
            trigger: "blur"
          },
        ],
        bankInfo: [
          { required: true, message: "开户行不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '开户行长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        bankAccount: [
          { required: true, trigger: 'blur', validator: bankAccountValid }
        ],
        contactUser: [
          { required: true, message: "联系人号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '联系人长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        contactNumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        weixin: [
          { required: true, message: "微信号不能为空", trigger: "blur" },
          { min: 3, max: 20, message: '微信号长度必须介于 3 和 20 之间', trigger: 'blur' }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listCustomer(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        unitName: null,
        unitAddress: null,
        creditCode: null,
        bankInfo: null,
        bankAccount: null,
        contactUser: null,
        contactNumber: null,
        email: null,
        weixin: null,
        post: null,
        status: "0",
        delFlag: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getCustomer().then(response => {
        this.open = true;
        this.title = "添加客户";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      const userId = Cookies.get("userId")
      getCustomer(customerId,userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + customerIds + '"的数据项？').then(function() {
        return delCustomer(customerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 客户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.unitName + '"客户吗？').then(function() {
        const userId = Cookies.get("userId")
        return changeCustomerStatus(userId,row.customerId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    contractManager(id){
      this.$router.push({path:'/system/contract',
        params:{
          customerId:id,
        } || this.redirect
      })
    }
  }
};
</script>
